import { View, Text } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { Button, Divider, Input, Space, Form } from '@nutui/nutui-react-taro'
import { login } from '@/apis/system'
import { LoginParams } from '@/apis/system/index.type'
import { storageKeySettings } from '@/configs/system'

import './index.less'

export default function Login () {
  const [form] = Form.useForm()

  useLoad(() => {
    console.log('Page loaded.')
  })

  async function onLoginTap() {
    const valid = await form.validateFields()
    if (valid.length === 0) {
      const values = form.getFieldsValue(['username', 'password']) as LoginParams
      try {
        Taro.showLoading({
          title: '登录中...',
          mask: true
        })
        const { status, data } = await login(values)
        console.log('login ', status, data)
        if (status === 0) {
          const { tokenInfo, tenants, user } = data;
          Taro.setStorageSync(storageKeySettings.token, tokenInfo.tokenValue);
          Taro.setStorageSync(storageKeySettings.tokenName, tokenInfo.tokenName);
          Taro.setStorageSync(storageKeySettings.user, user);
          const [tenant] = tenants;
          tenant && Taro.setStorageSync(storageKeySettings.tenantId, tenant.id);
          Taro.showToast({
            title: '登录成功',
            icon: 'success'
          }).then(() => {
            Taro.switchTab({ url: '/pages/index/index' })
          });
        }
      } catch (err) {
        Taro.showToast({
          title: '登录失败',
          icon: 'error'
        })
        console.error('login error:', err)
      } finally {
        Taro.hideLoading()
      }
    }
  }

  return (
    <View className='loginWrapper'>
      <View className='loginLogo'>
        <Text>智慧实验室</Text>
      </View>
      <Form form={form} 
      className='loginForm' 
       onFinish={onLoginTap}>
          <Space className='username'>
            <Text className='loginText'>用户</Text>
            <Divider direction="vertical" />
            <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                <Input placeholder='输入用户名' placeholderStyle='color: #8A909C' />
            </Form.Item>
          </Space>
        <Space className='password'>  
          <Text className='loginText'>密码</Text>
          <Divider direction="vertical" />
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input placeholder='输入密码' type="password" placeholderStyle='color: #8A909C' />
          </Form.Item>
        </Space>
        <View>
          <Button block type="primary" onClick={onLoginTap}>登 录</Button>
        </View>
      </Form>
    </View>
  )
}
